package io.gitee.chearnee.fw.socket.component;

import io.gitee.chearnee.fw.socket.NettyServerBootstrap;
import io.gitee.chearnee.fw.socket.handler.BizCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationFailedEvent;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;

import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;


public class NettyEventListener {
    //   @Autowired
//    private NettyProperties nettyProperties;
    @Autowired
    private NettyServerBootstrap nettyServerBootstrap;

    @EventListener(ApplicationStartedEvent.class)
    public void started(ApplicationStartedEvent applicationStartedEvent) {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> bizMap = applicationStartedEvent.getApplicationContext().getBeansWithAnnotation(BizCode.class);
        for (Map.Entry<String, Object> entry : bizMap.entrySet()) {
            Object object = entry.getValue();
            Class c = object.getClass();
            Annotation[] annotations = c.getDeclaredAnnotations();
            for (Annotation annotation : annotations) {
                if (annotation.annotationType().equals(BizCode.class)) {
                    BizCode biz = (BizCode) annotation;
                    map.put(biz.value(), object);
                }
            }
        }
        NettyDispatcher.getInstance().setBizMaps(map);
//        NettyDispatcher nettyDispatcher = applicationStartedEvent.getApplicationContext()
//            .getBean(NettyDispatcher.class);
//        nettyDispatcher.setBizMaps(map);
    }
    @EventListener(ApplicationReadyEvent.class)
    public void  ready(){
        // nettyServerBootstrap = new NettyServerBootstrap(nettyProperties);
        try {
            nettyServerBootstrap.run();
        } catch (Exception e) {
            e.printStackTrace();
            nettyServerBootstrap.destroy();
        }
    }

    @EventListener({ApplicationFailedEvent.class,ContextClosedEvent.class})
    public void  stop(){
        nettyServerBootstrap.destroy();
    }
}
